package my.edu.websocket;

import cn.hutool.core.bean.BeanUtil;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import my.edu.common.utils.RedisUtils;
import my.edu.model.User.entity.User;
import my.edu.model.User.service.IUserService;
import my.edu.security.shiroservice.ShiroService;
import my.edu.security.shiroservice.ShiroServiceImpl;
import my.edu.security.userEntity.UserDetail;
import my.edu.security.userEntity.UserToken;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;

import java.io.IOException;
import java.util.*;

@Component
@ServerEndpoint("/ws/notify/{id}")
public class BillWebSocket implements ApplicationContextAware {


    private static ApplicationContext applicationContext;

    private  ShiroServiceImpl shiroService;
    private  IUserService userService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BillWebSocket.applicationContext = applicationContext;
    }

    //存放会话对象
    private static Map<String, Map<Long,Session>> sessionMap = new HashMap();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("id") Long id) throws IOException {
        this.shiroService = applicationContext.getBean(ShiroServiceImpl.class);
        this.userService = applicationContext.getBean(IUserService.class);
        //获取用户权限信息
        UserToken token = shiroService.getToken(id);
        if (token == null){
            session.close();
        }
        User byId = userService.getById(id);
        Set<String> permissionList = shiroService.getUserPermissions(BeanUtil.copyProperties(byId, UserDetail.class));
        //根据权限信息存入map
        for (String string : permissionList) {
            String[] split = string.split(":");
            if (split[1].equals("audit")){
                if (sessionMap.containsKey(split[0])){
                    sessionMap.get(split[0]).put(id,session);
                }else {
                    HashMap<Long, Session> longSessionHashMap = new HashMap<>();
                    longSessionHashMap.put(id,session);
                    sessionMap.put(split[0], longSessionHashMap);
                }
            }
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {

    }

    /**
     * 连接关闭调用的方法
     *
     */
    @OnClose
    public void onClose( @PathParam("id")Long id) {
        User byId = userService.getById(id);
        Set<String> permissionList = shiroService.getUserPermissions(BeanUtil.copyProperties(byId, UserDetail.class));
        for (String string : permissionList) {
            String[] split = string.split(":");
            if (split[1].equals("audit")){
                if (sessionMap.containsKey(split[0])){
                    sessionMap.get(split[0]).remove(id);
                }
            }
        }
    }

    /**
     * 群发
     *
     * @param message
     */
    public void sendToAllClient(String billType,String message) {
        System.out.println("webSocket发消息");
        Map<Long, Session> longSessionMap = sessionMap.get(billType);
        for (Session session : longSessionMap.values()) {
            try {
                //服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



}
